The MIT License (MIT)
Copyright (c) 2014
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
%%html
<style>
div.input {
width: 105ex; /* about 80 chars + buffer */
}
div.text_cell {
width: 105ex /* instead of 100%, */
}
div.text_cell_render {
/*font-family: sans-serif;*/
font-family: serif; /* Make non-code text serif. */
line-height: 145%; /* added for some line spacing of text. */
width: 105ex; /* instead of 'inherit' for shorter lines */
}
/* Set the size of the headers */
div.text_cell_render h1 {
font-size: 18pt;
}
div.text_cell_render h2 {
font-size: 14pt;
}
.CodeMirror {
font-family: monospace;
}
</style>
%%javascript
IPython.OutputArea.auto_scroll_threshold = -1;
%matplotlib inline
import math
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np
from scipy import stats
#
figuresize = 20
plt.rcParams['figure.figsize'] = (1+math.sqrt(5))/2*figuresize, figuresize
plt.rcParams['figure.dpi'] = 200
plt.rcParams['font.size'] = 20
plt.rcParams['font.family'] = "serif"
plt.rcParams['text.usetex'] = "True"
#
land_color = 'gray'
water_color = 'white'
Get database and Python APIs to process the data from http://dev.maxmind.com/geoip/geoip2/geolite2/.
import geoip2.database
reader = geoip2.database.Reader('./geolocate_ip_data/GeoLite2-City.mmdb')
Read IP data into a list to iterate through to find the corresponding coordinates.
with open('./geolocate_ip_data/hacker_ips') as f:
IPs = f.read().splitlines()
Lookup each IP to find the corresponding latitude and longitude and count how many IPs were actually found.
x = []
y = []
missing = 0
for IP in IPs:
try:
response = reader.city(IP)
x.append(float(response.location.longitude))
y.append(float(response.location.latitude))
except:
print("IP address not found.")
missing += 1
found = len(x) - missing
IP address not found. IP address not found. IP address not found. IP address not found. IP address not found. IP address not found. IP address not found. IP address not found. IP address not found. IP address not found. IP address not found.
Create the maps. There are three maps: the "basemap" with the actual geography plotted, a plot of the points where IPs were geotraced to, and a density map (created with a Gaussian kernel density estimator) of the points (since there are lots of cases where points overlay each other or are otherwise obscured).
# Set map axis limits.
map_min_lat = -70
map_max_lat = 80
map_min_lon = -180
map_max_lon = 180
# Create map axes & base map.
fig, ax = plt.subplots()
map = Basemap(projection='merc', llcrnrlat=map_min_lat, urcrnrlat=map_max_lat,
llcrnrlon=map_min_lon, urcrnrlon=map_max_lon, resolution='l')
# Remap x and y coordinates into the map space projection.
xm,ym = map(x,y)
xmin, ymin = map(map_min_lon, map_min_lat)
xmax, ymax = map(map_max_lon, map_max_lat)
# Perform kernel density estimation calculation.
X, Y = np.mgrid[xmin:xmax:500j, ymin:ymax:500j]
positions = np.vstack([X.ravel(), Y.ravel()])
values = np.vstack([xm, ym])
kernel = stats.gaussian_kde(values)
Z = np.reshape(kernel(positions).T, X.shape)
# Create plots.
map.imshow(np.flipud(np.rot90(Z)), cmap=plt.cm.Reds,
extent=[xmin, xmax, ymin, ymax], alpha=0.6)
map.fillcontinents(color=land_color, lake_color=water_color,zorder=0)
map.plot(xm, ym,'k.',markersize=5)
plt.title(r"Point \& Relative Density Plot of " + str(found)
+ r" SSH Penetration Attempts")
fig = plt.gcf()
plt.show()
fig.savefig("test.png", bbox_inches=None, pad_inches=0.1)
reader.close()
import geoip2.database
reader = geoip2.database.Reader('./geolocate_ip_data/GeoLite2-City.mmdb')
x = []
y = []
missing = 0
found = 0
for IP in IPs:
try:
response = reader.city(IP)
if(response.country.name == 'Canada'):
x.append(float(response.location.longitude))
y.append(float(response.location.latitude))
found = found + 1
except:
print("IP address not found.")
missing += 1
print(found)
IP address not found. IP address not found. IP address not found. IP address not found. IP address not found. IP address not found. 72
# Set map axis limits.
map_min_lat = 40
map_max_lat = 83
map_min_lon = -150
map_max_lon = -50
# Create map axes & base map.
fig, ax = plt.subplots()
map = Basemap(projection='merc', llcrnrlat=map_min_lat, urcrnrlat=map_max_lat,
llcrnrlon=map_min_lon, urcrnrlon=map_max_lon, resolution='l')
# Remap x and y coordinates into the map space projection.
xm,ym = map(x,y)
xmin, ymin = map(map_min_lon, map_min_lat)
xmax, ymax = map(map_max_lon, map_max_lat)
# Perform kernel density estimation calculation.
X, Y = np.mgrid[xmin:xmax:500j, ymin:ymax:500j]
positions = np.vstack([X.ravel(), Y.ravel()])
values = np.vstack([xm, ym])
kernel = stats.gaussian_kde(values)
Z = np.reshape(kernel(positions).T, X.shape)
# Create plots.
map.imshow(np.flipud(np.rot90(Z)), cmap=plt.cm.Reds,
extent=[xmin, xmax, ymin, ymax], alpha=0.6)
map.fillcontinents(color=land_color, lake_color=water_color,zorder=0)
map.plot(xm, ym,'k.',markersize=5)
# Create label on point of interest.
for i, xmm in enumerate(xm):
if(y[i] > 55):
plt.text(xmm, ym[i], str(x[i]) + ", " + str(y[i]))
plt.title(r"Point \& Relative Density Plot of " + str(found)
+ r" SSH Penetration Attempts")
fig = plt.gcf()
plt.show()
fig.savefig("test2.png", bbox_inches=None, pad_inches=0.1)
reader.close()